<?php
class Core_Controller_Controllerloader {
	
	public function loadController($request, array $postVars){
		$parsed = $this->parseData($request);
		$page = $this->getPageName($parsed);
		$getVars = array();
		$getVars = $this->getVarsVariable($parsed);
		$target = $this->computePath($page);
		$this->getTarget($target, $page, $postVars);
	}
	
	public function getTarget($target, $page, array $postVars){
		try {
			if(file_exists($target)){
				include_once($target);
				
				$class = ucfirst($page) . '_Controller_' . ucfirst($page);
				if(class_exists($class)){
					$controller = new $class;
				}
				else {
					throw new Exception("Class does not exists!");
				}
			}
		}
		catch(Exception $e){
			echo $e->getMessage();
		}
		$controller->main($getVars);
	}
	
	/**
	 * computePath()
	 * create path to file
	 * 
	 * @param string $page
	 * @return string
	 */
	public function computePath($page){
		$target = basename(SERVER_ROOT) . "/" . "/controllers/" . $page . ".php";
		return $target;
	}
	
	/**
	 * getVarsVariable()
	 * get getVars array
	 * 
	 * @param multitype $parsed
	 * @return multitype:string
	 */
	public function getVarsVariable($parsed){
		$getVars = array();
		foreach($parsed as $argument){
			list($variable, $value) = split('=', $argument);
			$getVars[$variable] = urldecode($value);
		}
		return $getVars;
	}
	/**
	 * getPageName()
	 * get page name
	 * 
	 * @param multitype $parsed
	 * @return mixed
	 */
	public function getPageName($parsed){
		$page = array_shift($parsed);
		return $page;
	}
	
	/**
	 * parseData()
	 * parse request string
	 * 
	 * @param string $request
	 * @return multitype:
	 */
	public function parseData($request){
		$parsed = explode('&', $request);
		return $parsed;
	}
}